package normalObjects;

import java.util.Arrays;

/**
 * @author 26029
 * @date 2025/4/8
 * @description
 */
class PersonShallow implements Cloneable {
    String name;
    int age;
    int[] scores; // 引用类型成员变量

    public PersonShallow(String name, int age, int[] scores) {
        this.name = name;
        this.age = age;
        this.scores = scores;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); // 默认是浅拷贝
    }

    @Override
    public String toString() {
        return "PersonShallow{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", scores=" + Arrays.toString(scores) +
                '}';
    }
}

class PersonDeep implements Cloneable {
    String name;
    int age;
    int[] scores; // 引用类型成员变量

    public PersonDeep(String name, int age, int[] scores) {
        this.name = name;
        this.age = age;
        this.scores = scores;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        PersonDeep cloned = (PersonDeep) super.clone();
        cloned.scores = scores.clone(); // 深拷贝内部数组
        return cloned;
    }

    @Override
    public String toString() {
        return "PersonDeep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", scores=" + Arrays.toString(scores) +
                '}';
    }
}

public class LearnCopy {
    public static void main(String[] args) throws CloneNotSupportedException {
        // 浅拷贝
        PersonShallow ps1 = new PersonShallow("tom", 10, new int[]{1, 2, 3});
        PersonShallow ps2 = (PersonShallow) ps1.clone();
        System.out.println("ps1:" + ps1);
        System.out.println("ps2:" + ps2);
        // 修改ps1
        ps1.name = "alex";
        ps1.age = 15;
        ps1.scores[0] = 0;
        // 发现ps2的scores也变了
        System.out.println("ps1:" + ps1);
        System.out.println("ps2:" + ps2);

        // 深拷贝
        PersonDeep pd1 = new PersonDeep("tom", 10, new int[]{1, 2, 3});
        PersonDeep pd2 = (PersonDeep) pd1.clone();
        System.out.println("pd1:" + pd1);
        System.out.println("pd2:" + pd2);
        // 修改pd1
        pd1.name = "alex";
        pd1.age = 15;
        pd1.scores[0] = 0;
        // 发现pd2的都没变
        System.out.println("pd1:" + pd1);
        System.out.println("pd2:" + pd2);
    }
}

